<?php
/**
 * Created by PhpStorm.
 * User: yuyiwen
 * Date: 2018/9/20
 * Time: 下午2:15
 */

namespace app\index\controller;


use think\captcha\Captcha;
use think\Controller;
use think\Session;

class Log  extends Controller
{
    public $wb_access_token = null;
    // 显示注册页面
    public function reg ()
    {
        return view();
    }

    // 获取用户注册信息
    public function register ()
    {
        $post['username'] =  input('post.username' , '' , 'htmlspecialchars');
        $post['pwd'] =  input('post.pwd' , '' , 'trim');
        $post['repwd'] =  input('post.repwd');
        $post['phone'] =  input('post.phone');


        $phone_yzcode = input('post.phone_yzcode');

//        if ($phone_yzcode != session('code'))
//        {
//            $this->error('手机验证码错误');
//        }
//        if ($post['phone'] != session('phone'))
//        {
//            $this->error('输入的手机号码跟验证的手机号码不一致');
//        }

        $member = validate('member');
        if (!$member->check($post)) {
            $this->error($member->getError());
        }

        # 插入数据库
        $data = [
            'username' => $post['username'],
            'pwd' => md5($post['pwd']),
            'phone' => $post['phone']
        ];

        // 成为下级会员
        if (md5(session('pid') . '435ey6rftygubhj kl87i6trhfg') == session('pkey')) {
          $data['pid'] = session('pid');
        }



        $id= db('member')->insertGetId($data);
        if ($id)
            $this->success('注册成功！' , url('login') ,'');
        else
            $this->error('注册失败');
    }

    public function login ()
    {

        if ( input('id') && input('key') )
        {
            session('pid' , input('id' , '' , 'htmlspecialchars,intval'));
            session('pkey' , input('key' , '' , 'htmlspecialchars'));
        }



        # 微博登录
        $weibo_url = 'https://api.weibo.com/oauth2/authorize?client_id='.config('weibo')['app_key'].'&response_type=code&redirect_uri=http://yyw.weiyinstudio.com/?backurl='.url('wbLog' , '' , true , true);
        $this->assign('weibo_url' , $weibo_url);
        return view();
    }

    public function wbLog ()
    {
        # 获取"中转站"传递过来的code
        $code = input('get.code');
        $token = cache('wb_token');
        if (!$token){
            # 组装第二步url （通过code 换取 accesstoken）
            $url = 'https://api.weibo.com/oauth2/access_token?client_id=' . config('weibo')['app_key'] . '&client_secret=' . config('weibo')['app_sec'] . '&grant_type=authorization_code&redirect_uri=http://yyw.weiyinstudio.com/&code=' . $code;
            # 通过curl 模拟post请求
            $res = curl($url, '...');
            $token = json_decode($res, true);
            cache('wb_token', $token, 3000);
        }
        # 通过 accesstoken 换取用户信息
        $url = 'https://api.weibo.com/2/users/show.json?access_token='.$token['access_token'].'&uid='.$token['uid'];
        $user_info = curl($url);
        $user_info = json_decode($user_info , true);
        # 保存微博用户信息
        session('weibo_info' , $user_info);

        # 判断当前用户是否存在与会员表中。 当这个用户不存在会员表内，需要先绑定手机号码
        $hasUser = db('member')->where('weibo_id' , session('weibo_info')['id'])->find();
        if (!$hasUser) {
            # 用户表中不存在微博用户
            return view('bind_phone');
        }
        session('id' , $hasUser['id']);
        session('nickname' , $hasUser['nickname']);

        $this->success('恭喜，登录成功' , url('user/user'));
    }

    public function checkPhone ()
    {
        $post['phone'] =  input('post.phone');

        $phone_yzcode = input('post.phone_yzcode');

//        if ($phone_yzcode != session('code'))
//        {
//            $this->error('手机验证码错误');
//        }
//        if ($post['phone'] != session('phone'))
//        {
//            $this->error('输入的手机号码跟验证的手机号码不一致');
//        }

        # 查看会员表中是否已经存在该手机号码。（存在就代表会员有使用过其它方式注册过，只需要更新记录即可。 不存在就添加记录）
        $hasPhone = db('member')->where('phone' , $post['phone'])->find();
        $data = [
            'nickname' => session('weibo_info')['screen_name'],
            'weibo_id'=> session('weibo_info')['id'],
            'header_img' => session('weibo_info')['profile_image_url'],
        ];
        if (!$hasPhone) {
            // 会员不存在， 新增
            $data['phone'] = $post['phone'];
            db('member')->insertGetId($data);
        }else {
            // 更新
            db('member')->where('phone' , $post['phone'])->update($data);
        }



        # 重新查出会员数据
        $userInfo = db('member')->where('phone' , $post['phone'])->find();
//        dump($userInfo);

        session('id' , $userInfo['id']);
        session('nickname' , $userInfo['nickname']);

        $this->success('恭喜，登录成功' , url('user/user'));


    }

    public function checklog()
    {
        $data['username'] = input('post.username' , '' , 'htmlspecialchars');
        $data['pwd'] = md5(input('post.pwd' , '' , 'trim'));
        $hasmember = db('member')->where($data)->find();
        if ($hasmember['pid'] == 0 && $hasmember['is_agent'] == 0)
        {
            if (md5(session('pid') . '435ey6rftygubhj kl87i6trhfg') == session('pkey')) {
                db('member')->where(['id'=>$hasmember['id']])->update(['pid' => session('pid')]);
            }

        }
        if ($hasmember) {
            session('nickname' , $hasmember['nickname']);
            session('username' , $hasmember['username']);
            session('id' , $hasmember['id']);

            $this->success('登录成功' , url('user/user') );
        }else {
            $this->error('登录失败');
        }
    }

    // 验证码
    public function yzcode ()
    {
        $config = [
            'codeSet' => '123',
//            'useImgBg' => true
            'length' => 1,
            'useCurve' => false,
            'useNoise' => false
        ];
       $captcha =  new Captcha($config);
       return $captcha->entry();
    }

    // 退出登录
    public function logout ()
    {
        Session::delete('nickname');
        Session::delete('username');
        Session::delete('id');
        $this->error('退出成功' , url('index/index'));
    }

    // 发送验证码
    public function send_phone_msg ()
    {
        $yzcode =  input('get.yzcode');
        if(!captcha_check($yzcode)){
            //验证失败
            $this->error('验证码错误');
        }


        $phone = input('get.phone');
        $member = validate('member');
        $post['phone'] = $phone;
        if (!$member->scene('check_phone')->check($post)) {
            $this->error($member->getError());
        }

        $code = mt_rand(1000 , 9999);
        $config = ['expire' => 60 * 15];
        $session = new Session($config);
        $session::set('code' , $code);
        session('phone' , $phone);
        # 聚合数据的短信验证接口
        $url = 'http://v.juhe.cn/sms/send?mobile='.$phone.'&tpl_id=103033&tpl_value=%23code%23%3D'.$code.'&key=2f524705d0380ff37b64dda6fe032266';
        $res = curl($url);
        $return = json_decode( $res, true);
        return $return;
//        if ( $return['error_code'] == 0 )
//        {
//            // 验证码发送成功
//        }
    }

}